<script setup>
import { ref, reactive, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { sendVerificationCode, verifyResetCode, resetPassword } from '../api/User.js';

const router = useRouter();

// 消息提示状态
const message = ref({
  show: false,
  text: '',
  type: 'info' // success, error, info
});

// 显示消息提示（自动消失）
const showMessage = (text, type = 'info', duration = 3000) => {
  message.value = { show: true, text, type };
  setTimeout(() => {
    message.value.show = false;
  }, duration);
};

// 步骤控制：1-验证邮箱 2-设置新密码
const step = ref(1);
const countdown = ref(0);

// 表单数据
const form = reactive({
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证错误信息
const formErrors = reactive({
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
});

// 验证按钮状态计算
const canVerify = computed(() => {
  return form.email && form.verificationCode.length === 6;
});

// 表单整体有效性
const isFormValid = computed(() => {
  if (step.value === 1) {
    return !formErrors.email && !formErrors.verificationCode && canVerify.value;
  } else {
    return !formErrors.newPassword && !formErrors.confirmPassword &&
      form.newPassword && form.confirmPassword;
  }
});

// 监听表单变化进行验证
watch(form, () => {
  validateForm();
});

// 表单验证函数
const validateForm = () => {
  // 邮箱验证
  formErrors.email = form.email
    ? (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email) ? '' : '请输入有效的邮箱地址')
    : '邮箱不能为空';

  // 验证码验证（当有输入时）
  if (form.verificationCode) {
    formErrors.verificationCode = form.verificationCode.length === 6
      ? ''
      : '验证码为6位数字';
  } else {
    formErrors.verificationCode = '';
  }

  // 密码验证（第二步时）
  if (step.value === 2) {
    formErrors.newPassword = form.newPassword
      ? (form.newPassword.length >= 6 ? '' : '密码长度至少为6位')//有form.newPassword就这个
      : '新密码不能为空';//没有就这个

    formErrors.confirmPassword = form.confirmPassword
      ? (form.confirmPassword === form.newPassword ? '' : '两次输入的密码不一致')
      : '请确认新密码';
  }
};

// 发送验证码
const sendCode = async () => {
  // 邮箱格式预验证
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
    formErrors.email = '请输入有效的邮箱地址';
    return;
  }

  if (countdown.value > 0) return;

  try {
    const result = await sendVerificationCode({ emailTo: form.email });
    if (result.code === 1) {
      showMessage('验证码已发送至邮箱，请注意查收', 'success');
      startCountdown();
    } else {
      showMessage(result.message || '发送验证码失败', 'error');
      if (result.message === "邮箱不存在，请先注册！") {
        setTimeout(() => {
          router.push('/register');
        }, 1500); // 延迟跳转，让用户看到提示
      }
    }
  } catch (error) {
    showMessage('发送失败: ' + error.message, 'error');
  }
};

// 倒计时功能
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 验证验证码
const verifyCode = async () => {
  validateForm();
  if (!isFormValid.value) {
    showMessage("请先输入正确的邮箱和验证码", 'info');
    return;
  }

  try {
    const result = await verifyResetCode({
      code: form.verificationCode
    });
    if (result.code === 1) {
      showMessage('邮箱验证通过，请设置新密码', 'success');
      step.value = 2;
    } else {
      showMessage(result.message || '验证码验证失败', 'error');
    }
  } catch (error) {
    showMessage('验证失败: ' + error.message, 'error');
  }
};

// 处理密码重置
const handleResetPassword = async () => {
  validateForm();
  if (!isFormValid.value) return;

  try {
    const result = await resetPassword({
      email: form.email,
      newPassword: form.newPassword,
    });
    if (result.code === 1) {
      showMessage('密码重置成功，即将跳转到登录页', 'success', 2000);
      setTimeout(() => {
        router.push('/login');
      }, 2000);
    } else {
      showMessage(result.message || '密码重置失败', 'error');
    }
  } catch (error) {
    showMessage('重置失败: ' + error.message, 'error');
  }
};
</script>




<template>
  <div class="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
    <!-- 提示消息组件 -->
    <div v-if="message.show" :class="['fixed top-6 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300',
      message.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' :
        message.type === 'error' ? 'bg-red-50 text-red-700 border border-red-200' :
          'bg-blue-50 text-blue-700 border border-blue-200']">
      <p class="flex items-center gap-2">
        <i v-if="message.type === 'success'" class="icon-check-circle"></i>
        <i v-if="message.type === 'error'" class="icon-exclamation-circle"></i>
        <span>{{ message.text }}</span>
      </p>
    </div>

    <!-- 登录卡片 -->
    <div
      class="max-w-md w-full space-y-8 bg-white/95 backdrop-blur-sm rounded-xl shadow-lg overflow-hidden transform transition-all duration-300 hover:shadow-2xl">
      <div class="relative overflow-hidden">
        <div class="absolute top-0 right-0 -mt-16 -mr-16 w-32 h-32 bg-green-400/20 rounded-full blur-2xl"></div>
        <div class="relative p-8">
          <!-- 标题 -->
          <h2 class="text-center text-2xl font-semibold text-gray-800 mb-8 relative">
            重置密码
            <span
              class="absolute bottom-[-8px] left-1/2 transform -translate-x-1/2 w-12 h-1 bg-green-500 rounded"></span>
          </h2>

          <!-- 表单 -->
          <form @submit.prevent="handleResetPassword" class="relative z-10">
            <!-- 邮箱输入区域 -->
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-1">绑定邮箱</label>
              <div class="flex">
                <input type="email" v-model="form.email" required placeholder="请输入注册时的邮箱"
                  class="flex-1 px-4 py-3 focus:outline-none rounded-l-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50"
                  :disabled="step !== 1">
                <button type="button" @click="sendCode"
                  class="px-4 py-3 bg-green-400 text-white font-medium rounded-r-lg shadow hover:bg-green-600 transition-colors"
                  :disabled="countdown > 0 || step !== 1 || !form.email">
                  {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
                </button>
              </div>
              <p class="text-red-500 text-xs mt-1">{{ formErrors.email }}</p>
            </div>

            <!-- 验证码输入区域 -->
            <div class="mb-4" v-if="step >= 1">
              <label class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
              <input type="text" v-model="form.verificationCode" required maxlength="6" placeholder="请输入验证码"
                class="w-full px-4 py-3 focus:outline-none rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50"
                :disabled="step !== 1">
              <p class="text-red-500 text-xs mt-1">{{ formErrors.verificationCode }}</p>
            </div>

            <!-- 验证按钮 -->
            <button type="button" @click="verifyCode"
              class="w-full py-3 mb-6 bg-gradient-to-r from-green-500 to-green-600 text-white font-medium rounded-lg shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300"
              :disabled="step !== 1 || !canVerify" v-if="step === 1">
              验证邮箱
            </button>

            <!-- 密码输入区域 (验证通过后显示) -->
            <div v-if="step === 2">
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                <input type="password" v-model="form.newPassword" required minlength="6" placeholder="请输入新密码"
                  class="w-full px-4 py-3 focus:outline-none rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
                <p class="text-red-500 text-xs mt-1">{{ formErrors.newPassword }}</p>
              </div>

              <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                <input type="password" v-model="form.confirmPassword" required minlength="6" placeholder="请确认新密码"
                  class="w-full px-4 py-3 focus:outline-none rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
                <p class="text-red-500 text-xs mt-1">{{ formErrors.confirmPassword }}</p>
              </div>
            </div>

            <!-- 提交按钮 -->
            <button type="submit"
              class="w-full py-3 px-4 bg-gradient-to-r from-green-500 to-green-600 text-white font-medium rounded-lg shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300"
              :disabled="!isFormValid || step !== 2" v-if="step === 2">
              重置密码
            </button>

            <!-- 跳转登录 -->
            <div class="mt-6 text-center text-gray-600 text-sm">
              想起密码了? <router-link to="/login"
                class="text-green-600 font-medium hover:text-green-700  transition-colors">返回登录</router-link>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
/* 基础样式补充 */
.icon-check-circle {
  color: #10b981;
}

.icon-exclamation-circle {
  color: #ef4444;
}
</style>